<template>
  <div class="category">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <van-search
        v-model="searchValue"
        placeholder="搜索分类商品"
        shape="round"
        background="#f8f8f8"
        @search="onSearch"
      />
    </div>

    <div class="category-content">
      <!-- 左侧一级分类 -->
      <div class="category-sidebar">
        <div
          v-for="category in categories"
          :key="category.id"
          class="category-item"
          :class="{ active: activeCategory === category.id }"
          @click="selectCategory(category.id)"
        >
          <van-icon :name="category.icon" size="16" />
          <span>{{ category.name }}</span>
        </div>
      </div>

      <!-- 右侧二级分类和商品 -->
      <div class="category-main">
        <!-- 二级分类 -->
        <div v-if="currentCategory?.children" class="sub-categories">
          <div class="sub-category-title">{{ currentCategory.name }}</div>
          <van-grid :column-num="3" :border="false" :gutter="8">
            <van-grid-item
              v-for="subCategory in currentCategory.children"
              :key="subCategory.id"
              @click="selectSubCategory(subCategory.id)"
              class="sub-category-item"
              :class="{ active: activeSubCategory === subCategory.id }"
            >
              <span class="sub-category-name">{{ subCategory.name }}</span>
            </van-grid-item>
          </van-grid>
        </div>

        <!-- 商品列表 -->
        <div class="products-section">
          <div class="products-header">
            <span class="products-count">共{{ filteredProducts.length }}件商品</span>
            <div class="sort-options">
              <van-dropdown-menu>
                <van-dropdown-item v-model="sortType" :options="sortOptions" />
              </van-dropdown-menu>
            </div>
          </div>

          <div class="products-grid">
            <div
              v-for="product in sortedProducts"
              :key="product.id"
              class="product-card"
              @click="goToProduct(product.id)"
            >
              <img :src="product.image" alt="商品图片" class="product-img" />
              <div class="product-info">
                <h4 class="product-title">{{ product.title }}</h4>
                <div class="product-price">¥{{ product.price }}</div>
                <div v-if="product.tag" class="product-tag">{{ product.tag }}</div>
              </div>
            </div>
          </div>

          <!-- 空状态 -->
          <van-empty
            v-if="filteredProducts.length === 0"
            description="暂无商品"
            image="search"
          />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useProductStore } from '@/stores/product'
import { showToast } from 'vant'

const router = useRouter()
const route = useRoute()
const productStore = useProductStore()

const searchValue = ref('')
const activeCategory = ref(1)
const activeSubCategory = ref<number | null>(null)
const sortType = ref('default')

// 排序选项
const sortOptions = [
  { text: '默认排序', value: 'default' },
  { text: '价格从低到高', value: 'price-asc' },
  { text: '价格从高到低', value: 'price-desc' },
  { text: '销量优先', value: 'sales' }
]

// 从store获取数据
const { categories, products, getCategoryById, getProductsByCategory } = productStore

// 当前选中的分类
const currentCategory = computed(() => getCategoryById(activeCategory.value))

// 过滤后的商品
const filteredProducts = computed(() => {
  let result = getProductsByCategory(activeCategory.value)
  
  // 如果有搜索关键词，进一步过滤
  if (searchValue.value.trim()) {
    result = result.filter(product =>
      product.title.toLowerCase().includes(searchValue.value.toLowerCase())
    )
  }
  
  return result
})

// 排序后的商品
const sortedProducts = computed(() => {
  const products = [...filteredProducts.value]
  
  switch (sortType.value) {
    case 'price-asc':
      return products.sort((a, b) => a.price - b.price)
    case 'price-desc':
      return products.sort((a, b) => b.price - a.price)
    case 'sales':
      // 这里可以根据实际的销量字段排序
      return products.sort((a, b) => (b.stock || 0) - (a.stock || 0))
    default:
      return products
  }
})

// 选择一级分类
const selectCategory = (categoryId: number) => {
  activeCategory.value = categoryId
  activeSubCategory.value = null
}

// 选择二级分类
const selectSubCategory = (subCategoryId: number) => {
  if (activeSubCategory.value === subCategoryId) {
    activeSubCategory.value = null
  } else {
    activeSubCategory.value = subCategoryId
  }
}

// 搜索功能
const onSearch = (value: string) => {
  if (value.trim()) {
    showToast(`搜索: ${value}`)
  }
}

// 跳转到商品详情
const goToProduct = (productId: number) => {
  router.push({
    name: 'ProductDetail',
    params: { id: productId }
  })
}

// 初始化
onMounted(() => {
  // 如果路由中有分类ID参数，设置为当前分类
  const categoryId = route.query.categoryId
  if (categoryId) {
    activeCategory.value = Number(categoryId)
  }
})
</script>

<style scoped>
.category {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding-bottom: 60px;
}

.search-bar {
  padding: 10px 16px;
  background: #f8f8f8;
  flex-shrink: 0;
}

.category-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.category-sidebar {
  width: 80px;
  background: #f8f8f8;
  overflow-y: auto;
  flex-shrink: 0;
}

.category-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16px 8px;
  cursor: pointer;
  border-bottom: 1px solid #eee;
  transition: all 0.3s ease;
}

.category-item.active {
  background: white;
  color: #1989fa;
}

.category-item span {
  margin-top: 4px;
  font-size: 12px;
  text-align: center;
  line-height: 1.2;
}

.category-main {
  flex: 1;
  background: white;
  overflow-y: auto;
}

.sub-categories {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.sub-category-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #333;
}

.sub-category-item {
  padding: 8px 0;
  cursor: pointer;
}

.sub-category-item.active .sub-category-name {
  color: #1989fa;
  font-weight: 600;
}

.sub-category-name {
  font-size: 14px;
  color: #666;
  transition: color 0.3s ease;
}

.products-section {
  padding: 16px;
}

.products-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.products-count {
  font-size: 14px;
  color: #666;
}

.sort-options {
  font-size: 14px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
}

.product-card {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
}

.product-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.product-img {
  width: 100%;
  height: 120px;
  object-fit: cover;
}

.product-info {
  padding: 12px;
  position: relative;
}

.product-title {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: #333;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-price {
  font-size: 16px;
  color: #ff4444;
  font-weight: 600;
}

.product-tag {
  position: absolute;
  top: 8px;
  right: 8px;
  background: #ff4444;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 4px;
}
</style>